package com.flute.icrawler.policy.updatepolicy.framework;

import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.flute.icrawler.app.service.CrawlService;
import com.flute.icrawler.policy.bdb.storage.IStorage;
import com.flute.icrawler.policy.updatepolicy.bean.PolicyURL;

public class PolicyScheduled implements IScheduled {
	private static final Logger LOGGER = Logger.getLogger(PolicyScheduled.class.getName());

	private static UpdatePolicyController controller = UpdatePolicyController.getInstance();

	private boolean isExecute = false;

	// 当前粒度的存储库
	private IStorage storage = null;

	// 调度执行周期(秒)
	private Integer period;

	// 粒度（分钟）
	private Integer policy;

	/**
	 * 
	 * @param storage
	 */
	public PolicyScheduled(Integer policy, Integer period, IStorage storage) {
		this.policy = policy;
		this.period = period;
		this.storage = storage;
	}

	/**
	 * 
	 * @param runnable
	 */
	public void execute() {
		try {
			controller.execute(new Runnable() {
				public void run() {
					pushAllUrl();
				}
			}, policy, period, TimeUnit.SECONDS);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("执行调度任务出错", e);
		}
	}

	/**
	 * 将内存数据库中的所有url送到池中
	 */
	private void pushAllUrl() {
		if (isExecute) {
			return;
		}
		synchronized (this) {
			isExecute = true;
			try {
				PolicyURL url = null;
				while ((url = (PolicyURL) storage.next(url == null ? null : url.getUrl())) != null) {
					long nowTime = System.currentTimeMillis();
					if ((nowTime - url.getUpdateTime()) >= policy * 60 * 1000) {
						url.setUpdateTime(nowTime);
						controller.addUrl(url);
						storage.lock();
						if (storage.isContains(url.getUrl())) {
							storage.put(url.getUrl(), url);
						}
						storage.unlock();
						CrawlService.getInstance().logResult("update", "将url加入pool进行更新处理url=" + url.getUrl());
						LOGGER.info(storage.getName() + "将url加入pool进行更新处理url=" + url.getUrl());
					}
				}
			} catch (Exception e) {
				LOGGER.error("Scheduled URL error!" + e);
			}
			isExecute = false;
		}
	}
}
